package com.cfpl.admin_service.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cfpl.DTO.PageQueryConditionDTO;
import com.cfpl.admin_service.VO.CurrentUserFresh;
import com.cfpl.admin_service.VO.LoginAdmin;
import com.cfpl.admin_service.VO.PageQueryCondition;
import com.cfpl.admin_service.mapper.RoleMapper;
import com.cfpl.admin_service.service.RoleService;
import com.cfpl.project_common.pojo.Admin;
import com.cfpl.project_common.pojo.Role;
import com.cfpl.project_common.result.BaseResult;
import com.cfpl.admin_service.service.AdminService;
import com.cfpl.project_common.util.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 管理员
 */
@RestController
@Slf4j
@RequestMapping("/admin")
@Api(tags = "管理员相关接口")
public class AdminController {

    @Resource
    private AdminService adminService;
    @Resource
    private RoleMapper roleMapper;
    @Value("${admin.headPath}")
    private String headPath;

    /**
     * 添加  TestSuccess
     * @param admin admin
     * @return string
     */
    @PostMapping("/insertAdminInfo")
    @ApiOperation("新增管理员,角色只需要RoleID")
    public BaseResult insertAdminInfo(@RequestBody Admin admin){
        adminService.insertAdmin(admin);
        return BaseResult.ok();
    }

    /**
     * 分页查询 TestSuccess
     * 查询条件 姓名，手机号，邮箱
     */
    @PostMapping("/pageQueryAdmin")
    @ApiOperation("条件分页查询管理员")
    public BaseResult<PageQueryCondition> pageQueryAdmin(@RequestBody PageQueryConditionDTO pageConditionDTO){
        Page<Admin> adminPage = adminService.queryPage(
                pageConditionDTO.getCurrentPage(),
                pageConditionDTO.getPageSize(),
                pageConditionDTO.getQueryCondition());
        PageQueryCondition queryCondition = new PageQueryCondition(adminPage, pageConditionDTO.getQueryCondition());
        return BaseResult.ok(queryCondition);
    }

    /**
     * 登录者的姓名、角色id、头像？
     * @return 登录用户信息
     */
    @ApiOperation("通过token获取用户部分信息")
    @GetMapping("/getCurrentUserInfo")
    public BaseResult getCurrentUserInfo(){
        LoginAdmin loginAdmin = (LoginAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<Role> roleList = roleMapper.queryRolesInfoByAdminId(loginAdmin.getAdmin().getAdminId());
        List<Long> roleIdList = roleList.stream().map(Role::getRoleId).collect(Collectors.toList());
        CurrentUserFresh currentUser =  new CurrentUserFresh(roleIdList, loginAdmin.getUsername(), loginAdmin.getAdmin().getAdminHeadpic());
        return BaseResult.ok(currentUser);

    }

    /**
     * 更改管理员状态 TestSuccess
     * @param adminId 管理员ID
     */
    @DeleteMapping("/updateAdminStatus/{id}")
    @ApiOperation("更改管理员状态")
    public BaseResult updateAdminStatus(@PathVariable("id") Long adminId){
        adminService.adminSwitch(adminId);
        return BaseResult.ok();
    }

    /**
     * 根据id查询 TestSuccess
     * @param adminId id
     * @return 管理员对象
     */
    @GetMapping("/queryAdmin/{id}")
    @ApiOperation("根据id查询管理员")
    public BaseResult<Admin> queryAdminById(@PathVariable("id") Long adminId){
        Admin admin = adminService.queryAdminById(adminId);
        return BaseResult.ok(admin);
    }

    /**
     * 更新管理员信息 手机号，邮箱，头像，名字 TestSuccess
     * @param admin 管理员对象
     * @return 状态
     */
    @PutMapping("/updateAdmin")
    @ApiOperation("更新管理员信息")
    public BaseResult updateAdminInfo(@RequestBody Admin admin){
        adminService.updateAdmin(admin);
        return BaseResult.ok();
    }

    /**
     * 更新管理员角色信息 TestSuccess
     * @param adminId 管理员编号
     * @param roleIds 角色编号列表
     * @return status
     */
    @PostMapping("/assignRoleToAdmin")
    @ApiOperation("更新管理员角色信息")
    public BaseResult updateAdminRoleInfo(Long adminId,Long[] roleIds){
        adminService.assignAdminRoles(adminId, roleIds);
        return BaseResult.ok();
    }


    /**
     * 上传用户头像
     * @param multipartFile 文件字节码
     * @param adminID       目标用户ID
     * 用Form-data格式
     * 文件格式   yyyyMMddHHssmmAdminID
     * @return 返回文件路径，前端请求本地图片
     */
    @ApiOperation("上传用户头像")
    @PostMapping("/uploadUserHeadPic")
    @Transactional(rollbackFor = Exception.class)
    public BaseResult uploadUserHeadPic(@RequestParam MultipartFile multipartFile,Long adminID) throws Exception {

        File file = new File(headPath);
        FileUtils.checkPathExisted(file);
        String filename = FileUtils.uploadPictureFile(headPath, multipartFile.getBytes(), adminID);
        adminService.updateAdminHeadPic(filename.substring(2),adminID);
        return BaseResult.ok();

//        adminService.checkPathExisted(file);
        //测试工具类
//        try (
//            FileOutputStream fos = new FileOutputStream(filename);
//            BufferedOutputStream bos = new BufferedOutputStream(fos)
//        )
//        String filename = headPath+DateUtil.format(new Date(),"yyyyMMddHHmmss")+adminID+".jpg";
//测试工具类   最终返回值：D:\xx\xx   截取第二位之后的交给数据库
//            bos.write(multipartFile.getBytes());
//            bos.flush();


    }













}
